﻿using HZYProject.Core.Repositories;
using HZYProject.Domain;
using HZYProject.Service.CourseServices;
using HZYProject.Service.QuestionServices;
using HZYProject.Service.TestPaperServices;
using HZYProject.Web.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HZYProject.Web.Controllers
{
    /// <summary>
    /// 试卷管理
    /// </summary>
    [Route("TestPaper")]
    public class TestPaperController : Controller
    {
        private readonly IRepository<TestPaper, Guid> _repository;
        private readonly ITestPaperService _testPaperService;
        private readonly IRepository<Course, Guid> _courseRepository;
        private readonly IQuestionService _questionService;
        private readonly IRepository<Chapter, Guid> _chapterRepository;

        public TestPaperController(IRepository<Chapter, Guid> chapterRepository, IQuestionService questionService, IRepository<Course, Guid> courseRepository, IRepository<TestPaper, Guid> repository, ITestPaperService testPaperService)
        {
            _repository = repository;
            _testPaperService = testPaperService;
            _questionService = questionService;
            _courseRepository = courseRepository;
            _chapterRepository = chapterRepository;
        }

        #region 首页分页查询
        [HttpGet("")]
        public IActionResult Index()
        {
            var list = _courseRepository.GetAllList();
            return View(list);
        }
        [HttpPost("")]
        public async Task<IActionResult> Index(UITestPaper tp)
        {
            try
            {
                GetTestPaperInput input = new GetTestPaperInput { ID = tp.TestPaperID, Title = tp.Title, Status = tp.Status, CourseID = tp.CourseID };
                var data = await _testPaperService.GetPaginatedResult(input);
                var list = data.Data.Select(x => new UITestPaper
                {
                    TestPaperID = x.TestPaperID,
                    Title = x.Title,
                    Content = x.Content,
                    Status = x.Status,
                    QCount = x.QCount,
                    CourseID = x.CourseID,
                    CourseName = x.Course.Title
                });
                return Json(new { code = 0, msg = "", data = list, count = data.TotalCount });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "查询出错:" + ex.Message, data = new List<UITestPaper>(), count = 0 });
            }
        }
        #endregion

        #region 添加
        [HttpGet("add")]
        public IActionResult Add()
        {
            var list = _courseRepository.GetAllList();
            return View(list);
        }
        [HttpPost("add")]
        public IActionResult Add(UITestPaper tp)
        {
            try
            {
                TestPaper t = new TestPaper();
                t.TestPaperID = Guid.NewGuid();
                t.Title = tp.Title;
                t.Status = tp.Status;
                t.QCount = tp.QCount;
                t.CourseID = tp.CourseID;
                _repository.Insert(t);
                return Json(new { success = true, msg = "添加成功" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, msg = ex.Message });
            }
        }
        #endregion

        #region 修改
        [HttpGet("edit")]
        public IActionResult Edit(Guid id)
        {
            var obj = _repository.FirstOrDefault(x => x.TestPaperID == id);
            ViewBag.CourseName = _courseRepository.GetAllList();
            return View(obj);
        }
        [HttpPost("edit")]
        public IActionResult Edit(UITestPaper tp)
        {
            try
            {
                if (ModelState.IsValid)//obj在形成对象时，是否全部符合注解中的规定
                {
                    var obj = _repository.FirstOrDefault(x => x.TestPaperID == tp.TestPaperID);
                    obj.Title = tp.Title;
                    obj.Status = tp.Status;
                    obj.QCount = tp.QCount;
                    obj.CourseID = tp.CourseID;
                    _repository.Update(obj);
                    return Json(new { success = true, msg = "修改成功" });
                }
                else
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    int i = 1;
                    foreach (var v in ModelState.Values)
                    {
                        foreach (var p in v.Errors)
                        {
                            sb.AppendFormat("{0}-{1};", i++, p.ErrorMessage);
                        }
                    }
                    return Json(new { success = false, msg = "服务端验证未通过," + sb });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, msg = ex.Message });
            }

        }
        #endregion

        #region 删除
        [HttpPost("remove/{id}")]
        public IActionResult Del(Guid id)
        {
            try
            {
                var obj = _repository.FirstOrDefault(x => x.TestPaperID == id);
                _repository.Delete(obj);
                return Json(new { success = true, msg = "删除成功" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, msg = ex.Message });
            }
        }
        #endregion

        #region 自动组卷
        [HttpPost("auto/{id}")]
        public IActionResult Auto(Guid id)
        {
            try
            {
                var obj = _repository.FirstOrDefault(x => x.TestPaperID == id);
                obj.Content = "";
                GetTestPaperInput input = new GetTestPaperInput { CourseID = obj.CourseID, QCount = obj.QCount };
                var str = _testPaperService.AddQuestion(input);
                obj.Content = str.Content;
                _repository.Update(obj);
                return Json(new { success = true, msg = "", count = str.QCount });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, msg = ex.Message });
            }
        }
        #endregion

        #region 手动组卷
        [HttpGet("manual")]
        public IActionResult Manual(Guid id)
        {
            var obj = _repository.FirstOrDefault(x => x.TestPaperID == id);
            var qid = obj.Content.Split(',');
            if (!(qid.Any(x => string.IsNullOrEmpty(x))))
            {
                ViewBag.Lists = _testPaperService.GetQuestions(qid);
            }
            return View(obj);
        }
        #endregion

        #region 删除试题
        [HttpPost("deleteQuestions")]
        public IActionResult DeleteQuestions(Guid id)
        {
            try
            {
                var obj = _repository.FirstOrDefault(x => x.TestPaperID == id);
                var qid = obj.Content.Split('|');
                obj.Content = "";
                _repository.Update(obj);
                return Json(new { success = true, msg = "", count = qid.Length });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = ex.Message
                });
            }
        }
        #endregion

        #region 查询试题
        [HttpGet("searchQuestion")]
        public IActionResult SearchQuestion(Guid id)
        {
            var list = _courseRepository.GetAllList();
            var obj = _repository.FirstOrDefault(x => x.TestPaperID == id);
            ViewBag.TestPaper = obj;
            return View(list);
        }
        [HttpPost("searchQuestion")]
        public async Task<IActionResult> SearchQuestion(UIQuestion c)
        {
            try
            {
                GetQuestionInput input = new GetQuestionInput { CourseID = c.CourseID };
                var data = await _questionService.GetPaginatedResult(input);
                return Json(new { code = 0, msg = "", data = data.Data, count = data.TotalCount });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "查询出错:" + ex.Message, data = new List<UIQuestion>(), count = 0 });
            }
        }
        #endregion

        #region 添加试题
        [HttpPost("addQuestion")]
        public IActionResult AddQuestion(string ids, Guid tid)
        {
            try
            {
                var obj = _repository.FirstOrDefault(x => x.TestPaperID == tid);
                obj.Content = ids;
                _repository.Update(obj);
                return Json(new { success = true, msg = "", count = ids.Length });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, msg = ex.Message });
            }
        }
        #endregion
    }
}
